package com.wuyou.securitydemo.service.impl;

import com.wuyou.securitydemo.component.CustomizedTokenService;
import com.wuyou.securitydemo.component.ValidateComponent;
import com.wuyou.securitydemo.config.AuthConfig;
import com.wuyou.securitydemo.domain.AuthDTO;
import com.wuyou.securitydemo.domain.TokenVO;
import com.wuyou.securitydemo.pwd.CustomizedPasswordAuthenticationToken;
import com.wuyou.securitydemo.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;

/**
 * AuthServiceImpl
 *
 * @Date 2025/4/10 15:39
 * @Author 无忧
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthConfig authConfig;

    @Autowired
    private ValidateComponent validateComponent;

    @Autowired
    private UserDetailsService customizedUserDetailsServiceImpl;
    @Autowired
    private AuthenticationUserDetailsService cacheUserDetailsServiceImpl;

    @Autowired
    private CustomizedTokenService tokenService;
    @Autowired
    private AuthenticationEntryPoint resourceAuthExceptionEntryPoint;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public TokenVO auth(AuthDTO authDTO) {
        // 1 验证码
        if (authConfig.getValidateCode()) {
//            validateComponent.validate(authDTO.getRandomStr(), authDTO.getValidateCode());
        }
        String username = authDTO.getUsername();
        // 2 验证用户
        // 使用UserDetailsService.loadByUsername()
        UserDetails userDetails = customizedUserDetailsServiceImpl.loadUserByUsername(username);
        if (userDetails == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if (!passwordEncoder.matches(authDTO.getPassword(), userDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        // 2 获取Token
        return tokenService.createToken(new CustomizedPasswordAuthenticationToken(userDetails, authDTO.getPassword()));
    }

    /**
     * 退出登录
     */
    @Override
    public void logout(String token) {
        tokenService.destroy(token);
    }
}
